/*
 * XX公司源代码，版权归XX公司所有。
 * 
 * 项目名称 : it-ogt-webcommonservice
 * 创建日期 : 2024年1月11日
 * 修改历史 : 
 *     1. [2024年1月11日]创建文件 by huangwu
 */
package com.hyt.it.ogt.kq.common.bm.enums.pay.nonTaxPay;


import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class BsRSASign
{
  private static final String KEY_ALGORITHM = "RSA";
  private static final String SIGNATURE_ALGORITHM = "MD5withRSA";

  public static String sign(String data, String privateKey, String signType)
  {
    try
    {
      return sign(data.getBytes(CharType.UTF8.value), privateKey, signType);
    } catch (Exception e) {
      e.printStackTrace();
      throw new IllegalAccessError("生成密钥签名失败");
    }
  }

  private static String sign(byte[] data, String privateKey, String signType)
  {
    byte[] keyBytes;
    try
    {
      keyBytes = BsBase64Util.decodeBase64(privateKey);

      PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);

      KeyFactory keyFactory = KeyFactory.getInstance("RSA");

      PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);

      Signature signature = Signature.getInstance("MD5withRSA");
      signature.initSign(priKey);
      signature.update(data);

      return BsBase64Util.encodeBase64String(
        BsBase64Util.encodeBase64String(signature.sign()));
    }
    catch (Exception e)
    {
      e.printStackTrace();
      throw new IllegalAccessError("生成密钥签名失败");
    }
  }

  public static boolean verifySign(String data, String publicKey, String sign)
  {
    if ((data == null) || (data.trim().length() == 0))
      return false;
    if ((publicKey == null) || (publicKey.trim().length() == 0))
      return false;
    if ((sign == null) || (sign.trim().length() == 0))
      return false;
    try
    {
      return verifySign(data.getBytes(CharType.UTF8.value), 
        BsBase64Util.decodeBase64(publicKey), 
        BsBase64Util.decodeBase64(BsBase64Util.decodeBase64(sign)));
    } catch (Exception e) {
      e.printStackTrace(); }
    return false;
  }

  private static boolean verifySign(byte[] data, byte[] publicKey, byte[] sign)
    throws Exception
  {
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    keyFactory = KeyFactory.getInstance("RSA");
    PublicKey pubKey = keyFactory.generatePublic(keySpec);

    Signature signature = Signature.getInstance("MD5withRSA");
    signature.initVerify(pubKey);
    signature.update(data);

    return signature.verify(sign);
  }


}